/*
 * Copyright 2016. chenshufei
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package sz.szsmk.citizencard.widget;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.Settings;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;

import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.fastjson.JSON;
import com.alipay.sdk.app.AuthTask;
import com.alipay.sdk.app.H5PayCallback;
import com.alipay.sdk.app.PayTask;
import com.alipay.sdk.util.H5PayResultModel;
import com.chenenyu.router.annotation.Route;
import com.example.caller.BankABCCaller;
import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.journeyapps.barcodescanner.CaptureActivity;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.apache.http.client.CookieStore;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import kotlin.Unit;
import kotlin.jvm.functions.Function0;
import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.ZHSZInit;
import sz.szsmk.citizencard.model.network.bean.AbcPayResult;
import sz.szsmk.citizencard.model.network.bean.JumpActivityEventBusBean;
import sz.szsmk.citizencard.model.network.bean.PayResult;
import sz.szsmk.citizencard.databinding.ActivityPuretextWebviewBinding;
import sz.szsmk.citizencard.dialog.SuccessDialog;
import sz.szsmk.citizencard.dialog.TwoButtonDialog;
import sz.szsmk.citizencard.entity.BankEntity;
import sz.szsmk.citizencard.entity.FileUploadEntity;
import sz.szsmk.citizencard.entity.IDCardEntity;
import sz.szsmk.citizencard.entity.PayJsonBean;
import sz.szsmk.citizencard.entity.SecurityReq;
import sz.szsmk.citizencard.entity.SecurityReqBody;
import sz.szsmk.citizencard.ioc.Compontent.DaggerCommonActivityComponent;
import sz.szsmk.citizencard.log.L;
import sz.szsmk.citizencard.model.network.WebShareRes;
import sz.szsmk.citizencard.model.network.bean.H5IntroRes;
import sz.szsmk.citizencard.model.network.bean.JumpActivityBean;
import sz.szsmk.citizencard.model.network.bean.WXPayBean;
import sz.szsmk.citizencard.model.network.bean.YSFBean;
import sz.szsmk.citizencard.model.network.bean.response.CardInfo;
import sz.szsmk.citizencard.model.network.bean.response.CheckIsChargeRes;
import sz.szsmk.citizencard.mvp.contract.IPureTextWebViewContact;
import sz.szsmk.citizencard.mvp.presenter.PureTextWebViewPresenter;
import sz.szsmk.citizencard.ui.activity.UserInfoActivity;
import sz.szsmk.citizencard.ui.activity.YouzanActivity;
import sz.szsmk.citizencard.ui.base.IBaseStatusBarActivity;
import sz.szsmk.citizencard.ui.dialogs.PrePermissionDialog;
import sz.szsmk.citizencard.ui.fragment.ElecCardSignDialog;
import sz.szsmk.citizencard.ui.fragment.YouzanFragment;
import sz.szsmk.citizencard.ui.newversion.activity.ScanQRCodeActivity;
import sz.szsmk.citizencard.ui.newversion.config.Constants;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.AndroidUtils;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.DataStoreUtils;
import sz.szsmk.citizencard.util.EsafeUtils;
import sz.szsmk.citizencard.util.JumpUtils;
import sz.szsmk.citizencard.util.PermissionUtil;
import sz.szsmk.citizencard.util.StringUtils;
import sz.szsmk.citizencard.util.Utils;
import sz.szsmk.citizencard.util.zxyh.CheckPermissionListener;
import sz.szsmk.citizencard.util.zxyh.DateUtils;
import sz.szsmk.citizencard.util.zxyh.DeviceUtils;
import sz.szsmk.citizencard.util.zxyh.FileUtils;
import sz.szsmk.citizencard.util.zxyh.HostAddress;
import sz.szsmk.citizencard.util.zxyh.JsonUtils;
import sz.szsmk.citizencard.util.zxyh.LoadingDialogUtils;
import sz.szsmk.citizencard.util.zxyh.MainController;
import sz.szsmk.citizencard.util.zxyh.OcrlibInterfaceImpl;

import static sz.szsmk.citizencard.util.DeviceUtil.getIpAddressString;

/**
 * <br /> author: chenshufei
 * <br /> date: 16/3/29
 * <br /> email: chenshufei2@sina.com
 */
@Route("webView")
public class PureTextWebViewActivity extends IBaseStatusBarActivity<PureTextWebViewPresenter, ActivityPuretextWebviewBinding>
        implements View.OnClickListener, IPureTextWebViewContact.IPureTextWebView  {
    TextView bjTv;
    TextView tv_title;
    private String mTitle;
    private WebView wv_content;
    private ImageView back;
    private TextView webTitle;
    private androidx.appcompat.widget.Toolbar toolBar;
    private ImageView shareImageView;//标题栏分享按钮

    //5.0以下使用
    private ValueCallback<Uri> uploadMessage;
    // 5.0及以上使用
    private ValueCallback<Uri[]> uploadMessageAboveL;

    private String orderInfo;
    private static final int SDK_PAY_FLAG = 19;
    private String url;
    private ProgressBar mProgress;
    private LinearLayout placeholder;
    /**
     * 启动身份证正面扫描请求码
     */
    public static final int REQUEST_CODE_IDCARD_SIDE_FRONT = 1;
    /**
     * 启动身份证背面扫描请求码
     */
    public static final int REQUEST_CODE_IDCARD_SIDE_BACK = 2;
    /**
     * 启动银行卡扫描请求码
     */
    public static final int REQUEST_CODE_BANK_CARD = 300000;
    public static final int WEBVIEW_ACTIVITY_CODE = 4;
    //读取手机状态请求码
    private static final int READ_PHONE_STATE_CODE = 5;
    //手机相机权限请求码
    private static final int FACE_CAMERA_REQUEST_CODE = 7;
    private LinearLayout mTitlelayout;

    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private String stt;
    //人脸识别object
    //安全中心请求
    SecurityReq securityReq;
    //身份认证请求
    SecurityReqBody securityReqBody;
    boolean firstLoad=true;
    //状态栏 高度
    View v_statusBar;
    private ArrayList<Object> list;
    private YSFBean ysfBean;
    private Intent intent;
    private String isNeedGetPermission;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_puretext_webview;
    }

    @Override
    protected void initInjector() {
        DaggerCommonActivityComponent.builder().appCompontent(DaggerApplication.getAppComponent())
                .build().inject(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //在生产环境，必须将此代码注释！
//        if(BuildConfig.DEBUG){
//            EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
//        }
//        if (ContextCompat.checkSelfPermission(PureTextWebViewActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
////            PermissionUtil.checkPermission(PureTextWebViewActivity.this,Manifest.permission.CAMERA,getResources().getString(R.string.camera_permission));
////        }

        EventBus.getDefault().register(this);

    }


    @Override
    protected void onResume() {
        super.onResume();
        String access_token = ACache.get(PureTextWebViewActivity.this).getAsString("access_token");
        String refresh_token = ACache.get(PureTextWebViewActivity.this).getAsString("refresh_token");
        Log.i("refresh_token",access_token+"  "+refresh_token);

        ABC_callBack();
    }

    @Override
    protected void updateViews() {
        //这里  mPresenter   不是null 了
    }
    private String returnUrl;
    private boolean isad;
    @SuppressLint("WrongViewCast")
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void initViews() {
        ImmersionBar.with(this)
                .fitsSystemWindows(true)
                .statusBarDarkFont(true, 0f)
                .statusBarColor(R.color.white).init();

        bjTv = findViewById(R.id.bj_tv);


        DeviceUtils.getSignature(this);
//        StatusBarUtil.setImmersiveStatusBar(this, true);
//        StatusBarUtil.setStatusBarColor(this, Color.WHITE);
        View titleLayout = findViewById(R.id.title_layout);
        wv_content = (WebView) findViewById(R.id.wv_content);
        mProgress = (ProgressBar) findViewById(R.id.web_progress);
        placeholder = (LinearLayout) findViewById(R.id.placeholder);
        back = (ImageView) findViewById(R.id.back);
        back.setOnClickListener(this);
        toolBar=(Toolbar)findViewById(R.id.toolbar);
        mFragments.add(YouzanFragment.getInstance());

        webTitle = (TextView) findViewById(R.id.setting_title);
        mTitlelayout = (LinearLayout) findViewById(R.id.title_layout);
        shareImageView = (ImageView) findViewById(R.id.share_iv);
        mTitle = getIntent().getStringExtra(Constant.TITLE);
        isad =  getIntent().getBooleanExtra("ad",false);
        stt = getIntent().getStringExtra("stt");
        if (mTitle != null) {
            if (mTitle.equals("我的订单")) {
                setStatusBar("blue");
                bjTv.setVisibility(View.VISIBLE);
                bjTv.setText("申请开票");
                bjTv.setTextColor(this.getResources().getColor(R.color.white));
                bjTv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        String access_token = ACache.get(PureTextWebViewActivity.this).getAsString("access_token");
//                        Bundle bundle = new Bundle();
//                        bundle.putString("url", Constant.BASE_URL + "app-front-end/#/myOrder/guide?isMain=1&access_token="+ access_token);
//                        bundle.putString(Constant.TITLE, "分类订单");
//                        JumpUtils.jumptoNatvie(PureTextWebViewActivity.this, "webView", 0, bundle);
                        String access_token = ACache.get(PureTextWebViewActivity.this).getAsString("access_token");
                        Bundle bundle = new Bundle();
//                        bundle.putString("url", Constant.BASE_URL + "app-front-end/#/myOrder/guide?isMain=1&access_token="+ access_token);
                        bundle.putString("url", Constant.BASE_URL+"app-front-end/#/invoice/apply?isMain=1");
                        bundle.putString(Constant.TITLE, "申请开票");
                        JumpUtils.jumptoNatvie(PureTextWebViewActivity.this, "webView", 0, bundle);

                    }
                });
            } else if (mTitle.equals("优惠券")) {
                mTitlelayout.setVisibility(View.VISIBLE);
                setStatusBar("blue");
                webTitle.setText(mTitle);
            } else if (mTitle.equals("申请开票")) {
                mTitlelayout.setVisibility(View.GONE);
                setStatusBar("white");
            }else {
                mTitlelayout.setVisibility(View.VISIBLE);
                setStatusBar("blue");
                bjTv.setVisibility(View.GONE);
            }
            if (mTitle.equals("转转卡")) {
                shareImageView.setVisibility(View.VISIBLE);
                setStatusBar("blue");
                shareImageView.setOnClickListener(this);
            }
        } else {
            mTitlelayout.setVisibility(View.GONE);
            setStatusBar("white");
        }
        //获取的url地址
        intent = getIntent();
        url = intent.getStringExtra("url");
        isNeedGetPermission = intent.getStringExtra("isNeedGetPermission");
//        Log.i("dizhi",url);


        boolean hideTop = getIntent().getBooleanExtra("hideTop", false);
        if (hideTop) {
            titleLayout.setVisibility(View.GONE);
        }
        WebSettings settings = wv_content.getSettings();
        wv_content.getSettings().setJavaScriptEnabled(true);
        wv_content.getSettings().setDomStorageEnabled(true);
        wv_content.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);
        wv_content.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
        wv_content.getSettings().setAppCachePath(appCachePath);
        wv_content.getSettings().setAllowFileAccess(true);
        wv_content.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        wv_content.getSettings().setUseWideViewPort(true);
        wv_content.getSettings().setAppCacheEnabled(true);
        wv_content.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        if (url.contains("ccb.com/CCBIS") || url.contains("ccb.com.cn/CCBIS")) {
        } else {
            Log.i("refresh_token","进入");
            wv_content.addJavascriptInterface(new JsInteration(), "android");
        }
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            wv_content.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        wv_content.getSettings().setBlockNetworkImage(false);

        String stringExtra = getIntent().getStringExtra(Constant.HMLC);
        if (stringExtra != null) {
            String userAgentString = wv_content.getSettings().getUserAgentString();
            String ua = wv_content.getSettings().getUserAgentString();
            String webUa = ua + "SZSMKBWDCNC20070509ED";
            L.e(Constant.TAG, "webVIew惠民理财：" + webUa);
            wv_content.getSettings().setUserAgentString(webUa);
        } else {
            String userAgentString = settings.getUserAgentString();
            String ua = userAgentString + "SZSMK";
            L.e(Constant.TAG, "webVIew代理：" + ua);
            wv_content.getSettings().setUserAgentString(ua);
        }

        //体育惠民设置自定义ua
        if (stt != null && stt.equals("stt")) {
            String ua = wv_content.getSettings().getUserAgentString() + "szsports_merchant/yd";
            wv_content.getSettings().setUserAgentString(ua);
        }
        settings.setBuiltInZoomControls(true);

        settings.setDatabaseEnabled(true);
        String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
        // 启用地理定位
        settings.setGeolocationEnabled(true);
        // 设置定位的数据库路径
        settings.setGeolocationDatabasePath(dir);
        // 最重要的方法，一定要设置，这就是出不来的主要原因 原因请看参考链接（Android WebView 无法打开天猫页面）
        settings.setDomStorageEnabled(true);

        boolean isNeedGetPermission = intent.getBooleanExtra("isNeedGetPermission", false);

        Log.e("getPermission",isNeedGetPermission+"");

        if (isNeedGetPermission){

        }else{
//            if (Build.VERSION.SDK_INT >= 23) {
//                int checkPermission = ContextCompat.checkSelfPermission(PureTextWebViewActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION);
//                if (checkPermission != PackageManager.PERMISSION_GRANTED) {
//                    ActivityCompat.requestPermissions(PureTextWebViewActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
//                    ActivityCompat.requestPermissions(PureTextWebViewActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
//                }
//            }
        }


        wv_content.setWebViewClient(new WebViewClient() {


            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                mProgress.setVisibility(View.GONE);
                wv_content.loadUrl("javascript:isNFC('"+AndroidUtils.hasNfc(PureTextWebViewActivity.this)+"')");
            }

            @Override
            public void onLoadResource(WebView view, String url) {
                if (url.contains("alipays")) {
                    try {
                        view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                    } catch (Exception e) {
                        Toast.makeText(PureTextWebViewActivity.this, "请确认手机已安装支付宝App!", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
                handler.proceed();
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
            }

            //转转卡支付宝拦截
            @Override
            public boolean shouldOverrideUrlLoading(final WebView view, String url) {
                Log.e("shouldOverrideUrl",url);
                Uri mUrl = Uri.parse(url);
                String scheme = mUrl.getScheme();


                //支付宝拦截
                if (url.startsWith("http:") || url.startsWith("https:")) {
                    return false;
                }
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                } catch (Exception e) {
                    //Log.e(TAG, " Exception is ==== >>> " + e);
                }

                if (url.startsWith("weixin://wap/pay?")) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    startActivity(intent);
                    return true;
                }
                if(url.indexOf("wx.tenpay")>-1){
                    if (("4.4.3".equals(android.os.Build.VERSION.RELEASE))
                            || ("4.4.4".equals(android.os.Build.VERSION.RELEASE))) {
                        //兼容这两个版本设置referer无效的问题
                        view.loadDataWithBaseURL(Constant.WX_Referer_yfb,
                                "<script>window.location.href=\"" + url + "\";</script>",
                                "text/html", "utf-8", null);
                    } else {
                        Map<String, String> extraHeaders = new HashMap<>();
                        extraHeaders.put("Referer", Constant.WX_Referer_yfb);
                        view.loadUrl(url, extraHeaders);
                    }
                    return true;
                }


                if (!(url.startsWith("http") || url.startsWith("https"))) {
                    return true;
                }

                final PayTask task = new PayTask(PureTextWebViewActivity.this);
                boolean isIntercepted = task.payInterceptorWithUrl(url, true, new H5PayCallback() {
                    @Override
                    public void onPayResult(final H5PayResultModel result) {
                        returnUrl = result.getReturnUrl();
                        if (!TextUtils.isEmpty(returnUrl)) {
                            runOnUiThread(() -> wv_content.loadUrl(returnUrl));
                        }
                    }
                });
                if (!isIntercepted) {
                    wv_content.loadUrl(url);
                }
                return true;
            }
        });
        //设置加载进度条
        wv_content.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                callback.invoke(origin, true, false);
                super.onGeolocationPermissionsShowPrompt(origin, callback);
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    mProgress.setVisibility(View.GONE);//加载完网页进度条消失
                } else {
                    mProgress.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                    mProgress.setProgress(newProgress);//设置进度值
                }
            }

            // For Android >= 5.0
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                uploadMessageAboveL = filePathCallback;
                //先检查权限
                checkPermission();
                return true;
            }
            @Override
            public void onReceivedTitle(WebView webview, String title) {
                super.onReceivedTitle(webview, title);
                if (url.contains("charge/main")) {
                    mTitlelayout.setVisibility(View.GONE);
                    setStatusBar("white");
                } else if (url.contains("payFail")) {
                    mTitlelayout.setVisibility(View.GONE);
                    setStatusBar("white");
                } else if (url.contains("card/main?")) {
                    mTitlelayout.setVisibility(View.GONE);
                    setStatusBar("white");
                } else if (url.contains("gardenCard/main")) {
                    mTitlelayout.setVisibility(View.GONE);
                    setStatusBar("white");
                } else if (url.contains("familyCard/availableScenerySpot")) {
                    mTitlelayout.setVisibility(View.GONE);
                    setStatusBar("white");
                } else if (url.contains("familycard/main")) {
                    mTitlelayout.setVisibility(View.GONE);
                    setStatusBar("white");
                } else if (url.contains("familyCard/main")) {
                    mTitlelayout.setVisibility(View.GONE);
                    setStatusBar("white");
                } else if (url.contains("myOrder/main")) {
                    mTitlelayout.setVisibility(View.VISIBLE);
                    setStatusBar("blue");
                } else if (url.contains("card/orderDetail")) {
                    mTitlelayout.setVisibility(View.VISIBLE);
                    setStatusBar("blue");
                } else if (url.contains("huodong.szsmk")) {
//                    mTitlelayout.setVisibility(View.VISIBLE);
                } else if (url.contains("h5/suzhou/")) {
                    mTitlelayout.setVisibility(View.VISIBLE);
                    setStatusBar("blue");
                } else if (url.contains("mine/coupons")) {
                    mTitlelayout.setVisibility(View.VISIBLE);
                    setStatusBar("blue");
                } else if (url.contains("wallet/main")) {
                    mTitlelayout.setVisibility(View.VISIBLE);
                    setStatusBar("blue");
                } else if (url.contains("/invoice/take")) {
                    mTitlelayout.setVisibility(View.GONE);
                    setStatusBar("white");
                } else if (url.contains("myorder/all?orderStatus")) {//
                    mTitlelayout.setVisibility(View.VISIBLE);
                    setStatusBar("blue");
                    if (url.contains("orderType=5")) {
                        webTitle.setText("云闪充充值");
                    } else if (url.contains("orderType=4")) {
                        webTitle.setText("转转卡充值");
                    } else if (url.contains("orderType=1")) {
                        webTitle.setText("休闲年卡充值");
                    } else if (url.contains("orderType=2")) {
                        webTitle.setText("亲子卡充值");
                    } else if (url.contains("orderType=10")) {
                        webTitle.setText("蛋糕卡充值");
                    }
                } else if (url.contains("/invoice/apply")) {
                    mTitlelayout.setVisibility(View.GONE);
                    setStatusBar("white");

                } else if (url.contains("/invoice/take")) {
                    mTitlelayout.setVisibility(View.GONE);
                    setStatusBar("white");
                } else if (url.contains("whxf")) {
                    mTitlelayout.setVisibility(View.VISIBLE);
                    setStatusBar("blue");
                } else if (url.contains("live/play")) {//增加快乐玩状态栏处理
                    mTitlelayout.setVisibility(View.VISIBLE);
                    setStatusBar("white");
                } else if (url.contains("/live/record")) {//预约记录的页面
                    mTitlelayout.setVisibility(View.VISIBLE);
                    setStatusBar("white");
                } else if (url.contains("/common/secretAgreement")) {//隐私协议
                    mTitlelayout.setVisibility(View.GONE);
                    setStatusBar("white");
                } else if (url.contains("/live/play")) {//景点预约
                    mTitlelayout.setVisibility(View.GONE);
                    setStatusBar("white");
                }else if (url.contains("m-lcpro.lianchuanghj.com")){
                    setStatusBar("blue");
                    mTitlelayout.setVisibility(View.VISIBLE);
                    webTitle.setText(title);
                }

                if (!TextUtils.isEmpty(title)) {
                    webTitle.setText(title);
                    if (title.contains("市民金融")) {
                        titleLayout.setVisibility(View.GONE);
                    } else if (title.contains("预约景点") || title.contains("景点预约") || title.contains("预约信息") || title.contains("预约记录")) {
                        titleLayout.setVisibility(View.GONE);
                    }
                }
                String cookiesString = CookieManager.getInstance().getCookie(url);
                if (null != cookiesString) {
                    String[] cookies = cookiesString.split(";");
                    for (String cookie : cookies) {
                        String[] cook = cookie.split("=");
                        if (null != cook && cook.length > 1) {
                            Cookie cookie1 = new BasicClientCookie(cook[0], cook[1]);
                            cookieStore.addCookie(cookie1);
                        }
                    }
                }
            }

        });
        wv_content.loadUrl(url);

//        wv_content.loadUrl("file:///android_asset/test123.html");

        if(url.contains("fund")){
            //公积金
            //不能截屏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
        }

//        wv_content.reload();
        String path = getIntent().getStringExtra(Constant.PATH);
        String webviewPathType = getIntent().getStringExtra(Constant.WEBVIEW_PATH_TYPE);
        String pageTitleType = getIntent().getStringExtra(Constant.PAGE_TITLE_TYPE);
        // assertHtmlFileName  比如 test.html
        wv_content.getSettings().setLoadsImagesAutomatically(true);
        wv_content.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);


        if (Constant.WEBVIEW_PATH_TYPE_LOCAL.equals(webviewPathType)) {
//            wv_content.loadUrl("file:///android_asset/"+path);


//            wv_content.loadUrl(url1);


        } else if (Constant.WEBVIEW_PATH_TYPE_URL.equals(webviewPathType)) {
//            wv_content.loadUrl(url1);
            //initWebs();
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            wv_content.getSettings().setAllowUniversalAccessFromFileURLs(true);//支持js读取本地json数据
        }
        if (Build.VERSION.SDK_INT > 10) {
            wv_content.removeJavascriptInterface("searchBoxJavaBridge_");
            wv_content.removeJavascriptInterface("accessibility");
            wv_content.removeJavascriptInterface("accessibilityTraversal");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CookieManager.getInstance().removeAllCookie();
        EventBus.getDefault().unregister(this);
    }

    public static final int PERMISSION_CAMEMA = 2009;


    //检查权限
    private void checkPermission() {

        if(XXPermissions.isGranted(this, Permission.READ_EXTERNAL_STORAGE,
                Permission.WRITE_EXTERNAL_STORAGE,Permission.CAMERA)){
            //正常打开
            openHeadDialog();
        }else{
            //自定义弹窗
            PrePermissionDialog dialog = PrePermissionDialog.Companion.newInstance(new Function0<Unit>() {
                @Override
                public Unit invoke() {
                    //授权
                    realPermission();
                    return null;
                }
            });
            dialog.show(this.getSupportFragmentManager(),"permission");
        }
    }

    private void realPermission(){
        XXPermissions.with(this)
                .permission(new String[]{
                        Permission.READ_EXTERNAL_STORAGE,
                        Permission.WRITE_EXTERNAL_STORAGE,Permission.CAMERA})
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            openHeadDialog();
                        } else {
                            Toast.makeText(PureTextWebViewActivity.this, "获取部分权限成功，但部分权限未正常授予", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            Toast.makeText(PureTextWebViewActivity.this, "被永久拒绝授权，请手动授予权限", Toast.LENGTH_SHORT).show();
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(PureTextWebViewActivity.this,permissions);
                        } else {
                            Toast.makeText(PureTextWebViewActivity.this, "获取权限失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }


    private void openHeadDialog(){
        new MaterialDialog.Builder(this)
                .items("拍照", "相册")
                .positiveText("取消")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if (uploadMessageAboveL != null) {
                            uploadMessageAboveL.onReceiveValue(null);
                            uploadMessageAboveL = null;
                        }
                        if (uploadMessage != null) {
                            uploadMessage.onReceiveValue(null);
                            uploadMessage = null;
                        }
                        dialog.dismiss();
                    }
                })
                .cancelable(false)
                .canceledOnTouchOutside(false)
                .itemsCallback(new MaterialDialog.ListCallback() {
                    @Override
                    public void onSelection(MaterialDialog dialog, View itemView, int position, CharSequence text) {
                        if (position == 0) {
                            if (Build.VERSION.SDK_INT >= 23 &&
                                    ContextCompat.checkSelfPermission(PureTextWebViewActivity.this,
                                            Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                                ActivityCompat.requestPermissions(PureTextWebViewActivity.this, new String[]{Manifest.permission.CAMERA}, PERMISSION_CAMEMA);
                            } else {
                                takeCamera(PureTextWebViewActivity.this);
                            }
                        } else if (position == 1) {
                            takePhoto();
                        }
                    }
                }).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case PERMISSION_CAMEMA:
                for (int i = 0; i < grantResults.length; i++) {
                    boolean isTip = ActivityCompat.shouldShowRequestPermissionRationale(PureTextWebViewActivity.this, permissions[i]);
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        takeCamera(PureTextWebViewActivity.this);
                    } else {
                        if (isTip) {
                            Toast.makeText(PureTextWebViewActivity.this, "当前无法使用该功能！", Toast.LENGTH_SHORT).show();
                        } else {
                            new AlertDialog.Builder(PureTextWebViewActivity.this)
                                    .setCancelable(false)
                                    .setMessage("当前已禁用摄像头功能，点击确定前往设置中打开位置权限！")
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                            Uri uri = Uri.fromParts("package", getPackageName(), null);
                                            intent.setData(uri);
                                            startActivityForResult(intent, 2001);
                                        }
                                    })
                                    .setNegativeButton("取消", null)
                                    .show();
                        }
                    }
                }
                break;
        }
    }

    //图片
    private final static int FILE_CHOOSER_RESULT_CODE = 128;
    //拍照
    private final static int FILE_CAMERA_RESULT_CODE = 129;
    //拍照图片路径
    private String cameraFielPath;

    private Uri imageUri;

    //选择图片
    private void takePhoto() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "Image Chooser"), FILE_CHOOSER_RESULT_CODE);
    }

    public static File tempFile;

    //拍照
    private void takeCamera(Activity activity) {
        //获取系统版本
        int currentapiVersion = Build.VERSION.SDK_INT;
        // 激活相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 判断存储卡是否可以用，可用进行存储
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            SimpleDateFormat timeStampFormat = new SimpleDateFormat(
                    "yyyy_MM_dd_HH_mm_ss");
            String filename = timeStampFormat.format(new Date());
            cameraFielPath = Environment.getExternalStorageDirectory() + "/" + filename + ".jpg";
            tempFile = new File(cameraFielPath);
            if (currentapiVersion < 24) {
                // 从文件中创建uri
                imageUri = Uri.fromFile(tempFile);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            } else {
                //兼容android7.0 使用共享文件的形式
                ContentValues contentValues = new ContentValues(1);
                contentValues.put(MediaStore.Images.Media.DATA, tempFile.getAbsolutePath());
                //检查是否有存储权限，以免崩溃
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    //申请WRITE_EXTERNAL_STORAGE权限
                    Toast.makeText(this, "请开启存储权限", Toast.LENGTH_SHORT).show();
                    return;
                }
                imageUri = activity.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            }
        }
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CAREMA
        activity.startActivityForResult(intent, FILE_CAMERA_RESULT_CODE);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (null != uploadMessage || null != uploadMessageAboveL) {
            if (resultCode != RESULT_OK) {//同上所说需要回调onReceiveValue方法防止下次无法响应js方法
                if (uploadMessageAboveL != null) {
                    uploadMessageAboveL.onReceiveValue(null);
                    uploadMessageAboveL = null;
                }
                if (uploadMessage != null) {
                    uploadMessage.onReceiveValue(null);
                    uploadMessage = null;
                }
                return;
            }
            Uri result = null;
            if (requestCode == FILE_CAMERA_RESULT_CODE) {
                if (null != data && null != data.getData()) {
                    result = data.getData();
                }
                if (result == null && hasFile(cameraFielPath)) {
                    result = Uri.fromFile(new File(cameraFielPath));
                }
                if (uploadMessageAboveL != null) {
                    uploadMessageAboveL.onReceiveValue(new Uri[]{result});
                    uploadMessageAboveL = null;
                } else if (uploadMessage != null) {
                    uploadMessage.onReceiveValue(result);
                    uploadMessage = null;
                }
            } else if (requestCode == FILE_CHOOSER_RESULT_CODE) {
                if (data != null) {
                    result = data.getData();
                }
                if (uploadMessageAboveL != null) {
                    onActivityResultAboveL(data);
                } else if (uploadMessage != null) {
                    uploadMessage.onReceiveValue(result);
                    uploadMessage = null;
                }
            }
        }
        if (REQUEST_CODE_IDCARD_SIDE_FRONT == requestCode) {
        } else if (REQUEST_CODE_IDCARD_SIDE_BACK == requestCode) {
        } else if (REQUEST_CODE_BANK_CARD == requestCode) {
        } else if (requestCode == WEBVIEW_ACTIVITY_CODE) {
            final String params = data.getStringExtra("PARAMS");
            //关闭webview回调
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    wv_content.loadUrl("javascript:closeWebViewResult('" + params + "')");
                }
            });
        }




        if (data!=null && data.hasExtra("pay_result")){
            //云闪付回调
            String pay_result = data.getExtras().getString("pay_result");
            if (pay_result.equalsIgnoreCase("success")){
                wv_content.loadUrl(Constant.BASE_URL
                        +"app-front-end/#/card/paySucc?orderId="+ysfBean.getOrderId()+"&tradeType="+ysfBean.getTradeType());
            }else if (pay_result.equalsIgnoreCase("fail")){
                wv_content.loadUrl(Constant.BASE_URL
                        +"app-front-end/#/payFail?orderId="+ysfBean.getOrderId()+"&tradeType="+ysfBean.getTradeType());
            }else if (pay_result.equalsIgnoreCase("cancel")){
                wv_content.loadUrl(Constant.BASE_URL
                        +"app-front-end/#/payFail?orderId="+ysfBean.getOrderId()+"&tradeType="+ysfBean.getTradeType());
            }
        }

    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(Intent intent) {
        Uri[] results = null;
        if (intent != null) {
            String dataString = intent.getDataString();
            ClipData clipData = intent.getClipData();
            if (clipData != null) {
                results = new Uri[clipData.getItemCount()];
                for (int i = 0; i < clipData.getItemCount(); i++) {
                    ClipData.Item item = clipData.getItemAt(i);
                    results[i] = item.getUri();
                }
            }
            if (dataString != null)
                results = new Uri[]{Uri.parse(dataString)};
        }
        uploadMessageAboveL.onReceiveValue(results);
        uploadMessageAboveL = null;
    }

    /**
     * 判断文件是否存在
     */
    public static boolean hasFile(String path) {
        try {
            File f = new File(path);
            if (!f.exists()) {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    //电子市民卡
    @Override
    public void onQRbuyCarSuccess(String id) {
        //跳转扫码乘车
        if (id.equals("2")) {
            mPresenter.checkIsCharge();
        } else {
            ElecCardSignDialog dialog = new ElecCardSignDialog();
            dialog.setAction(0);
            dialog.show(this.getFragmentManager(), null);
        }
    }

    @Override
    public void checkIsChargeSucc(CheckIsChargeRes ibaseBean) {
        String toJson = new Gson().toJson(ibaseBean);
        L.e(Constant.TAG, "checkIsCharge--->" + toJson);

        String code = ibaseBean.getCode();
        if (code.equals("0000")) {
            String isReCharge = ibaseBean.getData().getIsReCharge();
            if (isReCharge.equals("1")) {
                //这里 是 实名开 户后 认证 最后可以 进入下一个界面
                JumpUtils.jumptoNatvie(PureTextWebViewActivity.this,"dzsmk" , 0, null);

            } else if (isReCharge.equals("0")) {
                ElecCardSignDialog dialog = new ElecCardSignDialog();
                dialog.setAction(1);
                dialog.show(this.getFragmentManager(), null);
            }
        } else {
            SuccessDialog dialog = new SuccessDialog(this, ibaseBean.getMessage());
            dialog.show();
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    dialog.cancel();
                }
            }.start();
        }
    }

    @Override
    public void onFail(String msg) {

    }




    //h5调用客户端方法。
    public class JsInteration {

        //云闪充 支付宝支付
        @JavascriptInterface
        public void alipay(final String order) {
            L.e(Constant.TAG, "H5订单返回值：----》" + order);
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    L.e(Constant.TAG, "order====" + order);
                    orderInfo = order;
                    int start = order.indexOf("payExtend") + 12;
                    int end = order.indexOf("tradeType") - 3;
                    final String substring = order.substring(start, end);
                    L.e(Constant.TAG, "substring" + substring);
                    L.e(Constant.TAG, "orderInfo" + orderInfo);
                    Runnable payRunnable = new Runnable() {
                        @Override
                        public void run() {
                            PayTask alipay = new PayTask(PureTextWebViewActivity.this);
                            Map<String, String> result = alipay.payV2(substring, true);
                            Log.i("msp", result.toString());
                            Message msg = new Message();
                            msg.what = SDK_PAY_FLAG;
                            msg.obj = result;
                            mHandler.sendMessage(msg);
                        }
                    };

                    Thread payThread = new Thread(payRunnable);
                    payThread.start();
                }
            });
        }

        //教育E卡
        @JavascriptInterface
        public void jumptoZX(){
        }

        //微信支付
        @JavascriptInterface
        public void wxPay(String payBean){
            //后端来的数据
            wxPayBean = new Gson().fromJson(payBean, WXPayBean.class);
            Log.e("wxpay",payBean);
            list = new ArrayList<>();
            list.add(wxPayBean.getOrderId());
            list.add(wxPayBean.getTradeType());
            PayReq req = new PayReq();
            WXPayBean.CreatePayOrderResultDtoBean resultDto = wxPayBean.getCreatePayOrderResultDto();
            req.appId = ZHSZInit.INSTANCE.getAppId();
            req.partnerId=resultDto.getWxPartnerId();
            req.prepayId=resultDto.getPrepayId();
            req.nonceStr=resultDto.getNonceStr();
            req.timeStamp=resultDto.getTimeStamp();
            req.packageValue=("Sign=WXPay");
            req.sign=resultDto.getSign();
            IWXAPI wxapi = WXAPIFactory.createWXAPI(PureTextWebViewActivity.this, ZHSZInit.INSTANCE.getAppId());
            wxapi.registerApp(ZHSZInit.INSTANCE.getAppId());
            wxapi.sendReq(req);
        }

        //云闪付
        @JavascriptInterface
        public void ysfPay(String payBean){
            Log.e("ysfPay",payBean);
            ysfBean = new Gson().fromJson(payBean, YSFBean.class);
        }


        //扫码
        @JavascriptInterface
        public void scan(){
            Intent intent = new Intent(PureTextWebViewActivity.this, CaptureActivity.class);
            startActivityForResult(intent, 1110);
        }



        //订单
        @JavascriptInterface
        public void chargeOrders(String arg) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    String access_token = ACache.get(PureTextWebViewActivity.this).getAsString("access_token");
//            finish();
                    Bundle bundle = new Bundle();
                    bundle.putString(Constant.TITLE, "我的订单");
                    bundle.putString("url", Constant.BASE_URL + "app-front-end/#/charge/order?access_token=" + access_token);
                    JumpUtils.jumptoNatvie(PureTextWebViewActivity.this, "webView", 0, bundle);
                }
            });
        }


        @JavascriptInterface
        public void showMap(String name, String lat, String lon) {
            double latitude = StringUtils.convertToDouble(lat, 0);
            double longitude = StringUtils.convertToDouble(lon, 0);
            Utils.startMapBylocationByBaiduCorSys(PureTextWebViewActivity.this, latitude, longitude, name);
        }

        //省卡产品介绍与空中发卡
        @JavascriptInterface
        public void loadThirdPage(final String arg) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {

                    H5IntroRes h5IntroRes = new Gson().fromJson(arg, H5IntroRes.class);
                    String needHeader = h5IntroRes.getNeedHeader();
                    String url = h5IntroRes.getUrl().trim();
                    if (url != null) {
                        Bundle bundle = new Bundle();
                        if (needHeader.equals("1")) {
                            bundle.putString(Constant.TITLE, "");
                        }
                        bundle.putString("url", url);
                        Log.i("loadThirdPagemsg",url);
                        JumpUtils.jumptoNatvie(PureTextWebViewActivity.this
                                , "webView", 0, bundle);
                    }
                }
            });

        }

        //云闪充 充电宝
        @JavascriptInterface
        public void chargePal(String arg) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    JumpUtils.jump(PureTextWebViewActivity.this, "battery", 0);
                }
            });
        }


        //云闪充 智能手表
        @JavascriptInterface
        public void smartWatch(String arg) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
//                  Toast.makeText(PureTextWebViewActivity.this, "智能手表", Toast.LENGTH_SHORT).show();
                    final TwoButtonDialog dialog = new TwoButtonDialog(PureTextWebViewActivity.this, "开发中，敬请期待~");
                    dialog.setOnOkClickListener(new TwoButtonDialog.OnOkClickListener() {
                        @Override
                        public void onOkClick() {

                            dialog.cancel();
                        }
                    });
                    dialog.setOnCancelClickListener(new TwoButtonDialog.OnCancelClickListener() {
                        @Override
                        public void onCancelClick() {
//                    balanceDaoDao.deleteAll();
                            dialog.cancel();
//                    reFreshData();
                        }
                    });
                    dialog.show();

                }
            });
        }

        //H5各首页返回
        @JavascriptInterface
        public void goMainPage(String arg) {

            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    Log.e("wxpay11","退出");
                    finish();
                }
            });
        }

        //余额查询
        @JavascriptInterface
        public void balanceQuery(String arg) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    JumpUtils.jump(PureTextWebViewActivity.this, "querybalance", 0);
                }
            });
        }

        //分享  JS调用的接口
        @JavascriptInterface
        public void toShare(final String arg) {
            L.e(Constant.TAG, "分享+" + arg);
            String mJson = "";
            if (arg.substring(0, 1).equals("'")) {

                final String substring = arg.substring(1, arg.length() - 1);
                mJson = substring;
            } else {
                mJson = arg;
            }
            final String finalMJson = mJson;
            mHandler.post(new Runnable() {
                @Override
                public void run() {
//                    分三种分享方式 带配置参数有图 带配置参数无图 不带配置参数
                    L.e(Constant.TAG, "分享：web share args -> " + arg);
                    WebShareRes res = JSON.parseObject(finalMJson, WebShareRes.class);
                    if (!TextUtils.isEmpty(arg) || res != null) {
                        if (TextUtils.isEmpty(res.getIcon_url())) {
                            umShare(res.getShareTitle(),
                                    res.getShareDesc(),
                                    res.getLink_url(), R.mipmap.app_icon);
                        } else {
                            umShareNetImg(res.getShareTitle(),
                                    res.getShareDesc(),
                                    res.getLink_url(), res.getIcon_url());
                        }
                    } else {
                        umShare(wv_content.getTitle(),
                                wv_content.getTitle(),
                                wv_content.getUrl(), R.mipmap.app_icon);
                    }
                }
            });
        }

        //云闪充 服务网点
        @JavascriptInterface
        public void serviceOffice(final String arg) {
            L.e(Constant.TAG, "------" + arg);
//            Toast.makeText(PureTextWebViewActivity.this, "云闪充服务网点", Toast.LENGTH_SHORT).show();
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    Bundle bundle = new Bundle();
                    bundle.putString("key", arg);
                    bundle.putBoolean("recharge", true);//设置高亮云闪充筛选控件
                    JumpUtils.jumptoNatvie(PureTextWebViewActivity.this, "nerwork", 0, bundle);
                }
            });
        }

        //客服电话
        @JavascriptInterface
        public void tell(final String arg) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    Intent phoneIntent = new Intent(Intent.ACTION_DIAL,
                            Uri.parse("tel:" + arg));
                    startActivity(phoneIntent);
                }
            });
        }

        @JavascriptInterface
        public void toMyAddress(final String arg) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    L.e(Constant.TAG, "toMyAddress-----" + arg);
                    Toast.makeText(PureTextWebViewActivity.this, "选择地址", Toast.LENGTH_SHORT).show();
                    Bundle bundle = new Bundle();
                    bundle.putString("arg", arg);
                    bundle.putString("order", "order");
                    JumpUtils.jumptoNatvie(PureTextWebViewActivity.this, "adressadmin", 0, bundle);

                }
            });
        }

        //H5登录
        @JavascriptInterface
        public void login(String arg) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    ACache.get(DaggerApplication.getIns()).remove("access_token");
                    JumpUtils.jump(PureTextWebViewActivity.this, "login", 0);
                }
            });
        }

        //传入设备信息
        @JavascriptInterface
        public void getDeviceInfo() {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    String ip = getIpAddressString();
                    String id = AndroidUtils.getAndroidId(DaggerApplication.getIns());
                    wv_content.loadUrl("javascript:getDevice(" + ip + "," + id + ")");
                }
            });
        }

        //传给h5用户信息
        @JavascriptInterface
        public void requestZhszUserInfo(String str) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    String access_tokenNow = ACache.get(PureTextWebViewActivity.this).getAsString("access_token");
                    if(access_tokenNow==null){
                        JumpUtils.jump(PureTextWebViewActivity.this, "login", 0);

                        DataStoreUtils.INSTANCE.isLogin().observe(PureTextWebViewActivity.this, new Observer<Boolean>() {
                            @Override
                            public void onChanged(Boolean aBoolean) {
                                if(aBoolean){
                                    //重新登录后
                                    String access_token = ACache.get(PureTextWebViewActivity.this).getAsString("access_token");
                                    String refresh_token = ACache.get(DaggerApplication.getIns()).getAsString("refresh_token");
                                    wv_content.loadUrl("javascript:postZhszUserInfo('" + access_token + "','"+refresh_token+"')");
                                }
                            }
                        });
                    }else{
                        String refresh_token = ACache.get(DaggerApplication.getIns()).getAsString("refresh_token");
                        wv_content.loadUrl("javascript:postZhszUserInfo('" + access_tokenNow + "','"+refresh_token+"')");

                    }
                }
            });
        }

        //提示相机权限弹框
//        @JavascriptInterface
//        public void showPermiCamera(){
//            if (ContextCompat.checkSelfPermission(PureTextWebViewActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
//                PermissionUtil.checkPermission(PureTextWebViewActivity.this,Manifest.permission.CAMERA,getResources().getString(R.string.camera_permission));
//            }
//            boolean b = ContextCompat.checkSelfPermission(PureTextWebViewActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;
//            Toast.makeText(PureTextWebViewActivity.this, b+"", Toast.LENGTH_SHORT).show();
//            return ContextCompat.checkSelfPermission(PureTextWebViewActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;
//        }

        //提示电话权限弹框
        @JavascriptInterface
        public boolean showPermiPhone(String str){
            Toast.makeText(PureTextWebViewActivity.this, "...", Toast.LENGTH_SHORT).show();
            if (ContextCompat.checkSelfPermission(PureTextWebViewActivity.this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED){
                PermissionUtil.checkPermission(PureTextWebViewActivity.this,Manifest.permission.READ_PHONE_STATE,getResources().getString(R.string.camera_permission));
            }
            return ContextCompat.checkSelfPermission(PureTextWebViewActivity.this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED;
        }
        //提示电话权限弹框
        @JavascriptInterface
        public boolean showPermiPhone(){
            Toast.makeText(PureTextWebViewActivity.this, "...", Toast.LENGTH_SHORT).show();
            if (ContextCompat.checkSelfPermission(PureTextWebViewActivity.this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED){
                PermissionUtil.checkPermission(PureTextWebViewActivity.this,Manifest.permission.READ_PHONE_STATE,getResources().getString(R.string.camera_permission));
            }
            return ContextCompat.checkSelfPermission(PureTextWebViewActivity.this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED;
        }

        //加载有赞商城
        @JavascriptInterface
        public void showYouZanShop(final String arg) {
            final String substring = arg.substring(1, arg.length() - 1);
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    ACache.get(DaggerApplication.getIns()).remove("sykt");
                    ACache.get(DaggerApplication.getIns()).put("sykt", "sykt");
                    gotoActivity(substring);
                }
            });
        }

        //电子发票下载
        @JavascriptInterface
        public void showDzfp(final String arg) {
            final String mUrl = arg.substring(1, arg.length() - 1);
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.addCategory(Intent.CATEGORY_BROWSABLE);
                    intent.setData(Uri.parse(mUrl));
                    startActivity(intent);
                }
            });
        }

        //园林首页 订单
        @JavascriptInterface
        public void toMyOrder(String tour) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    String access_token = ACache.get(PureTextWebViewActivity.this).getAsString("access_token");
                    wv_content.reload();
                    String url1 = Constant.BASE_URL + "app-front-end/#/myOrder/main?access_token=" + access_token;
                    wv_content.loadUrl(url1);
                }
            });
        } //园林首页 订单

        @JavascriptInterface
        public void toBabyCard(String tour) {
            mHandler.post(new Runnable() {

                @Override
                public void run() {
                    String access_token = ACache.get(PureTextWebViewActivity.this).getAsString("access_token");
                    finish();
                    Bundle bundle = new Bundle();
                    String url = "http://huodong.szsmk.com/hd/2018/01/qinzi/index.php?cardno=";
                    bundle.putString("url", url);
                    JumpUtils.jumptoNatvie(PureTextWebViewActivity.this, "webView", 0, bundle);
                }
            });
        }

        //休闲年卡首页搜索
        @JavascriptInterface
        public void searchYearCard(String tour) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    String url = wv_content.getUrl();
                    Bundle bundle = new Bundle();
                    if (url.contains("familyCard")) {
                        bundle.putString("value", "familycard");
                    } else {
                        bundle.putString("value", "xxnk");
                    }
                    JumpUtils.jumptoNatvie(PureTextWebViewActivity.this, "search", 0, bundle);
                }
            });
        }

        //扫一扫
        @JavascriptInterface
        public void sys() {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    Bundle bundle = new Bundle();
                    JumpUtils.jumptoNatvie(PureTextWebViewActivity.this, "scanQRCode", 0, bundle);
                }
            });
        }

        //跳转系统设置
        @JavascriptInterface
        public void setLocation() {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivity(intent);
                }
            });
        }

        //根据参数 打开 指定的Activity
        @JavascriptInterface
        public void launcher(String json) {
            Log.i("launcher",json);
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    try {
                        JumpActivityBean jumpActivityBean = new Gson().fromJson(json, JumpActivityBean.class);
                        if(!TextUtils.isEmpty(jumpActivityBean.getActivity())){
                            switch (jumpActivityBean.getActivity()){
                                case "openFunction":
                                    ElecCardSignDialog dialog = new ElecCardSignDialog();
                                    dialog.setAction(Integer.parseInt(jumpActivityBean.getBundles().getString("type")));
                                    dialog.show(PureTextWebViewActivity.this.getFragmentManager(), null);
                                    break;
                                default:
                                    JumpUtils.jumptoNatvie(PureTextWebViewActivity.this,
                                            jumpActivityBean.getActivity(), 0, jumpActivityBean.getBundles());
                                    break;
                            }
                        }
                    }catch (Exception e){
                        Toast.makeText(PureTextWebViewActivity.this,"参数错误", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }

        //根据参数  调用 MainActivity的 EventBus方法
        @JavascriptInterface
        public void launcherEventBus(String json) {
            Log.i("launcherEventBus",json);
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    try {
                        JumpActivityEventBusBean jumpActivityBean = new Gson().fromJson(json, JumpActivityEventBusBean.class);
                        if(jumpActivityBean.getCode()!=0){
                            EventBus.getDefault().post(jumpActivityBean);
                        }
                    }catch (Exception e){
                        Toast.makeText(PureTextWebViewActivity.this,"参数错误", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }

        //支付宝sdk 支付
        @JavascriptInterface
        public void alipayBySDK(String data) {
            Runnable authRunnable = new Runnable() {
                @Override
                public void run() {
                    PayJsonBean payJsonBean = new Gson().fromJson(data,PayJsonBean.class);
                    AuthTask authTask = new AuthTask(PureTextWebViewActivity.this);
                    Map<String, String> result = authTask.authV2(payJsonBean.getPayExtend(), true);

                    Message msg = new Message();
                    //这里用 常量区分 是支付 还是授权
                    msg.what = SDK_PAY_FLAG;
                    msg.obj = result;
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("payJsonBean",payJsonBean);
                    msg.setData(bundle);
                    mHandlerAlipayBySDK.sendMessage(msg);
                }
            };
            // 必须异步调用
            Thread authThread = new Thread(authRunnable);
            authThread.start();
        }

        @JavascriptInterface
        public void jumpCakeCard(String data) {
            //手动跳蛋糕卡
            Bundle bundle = new Bundle();
            bundle.putString(ScanQRCodeActivity.SCAN_TYPE,ScanQRCodeActivity.PAY_CODE);
//            JumpUtils.jumptoNatvie(PureTextWebViewActivity.this,  Constants.SCANQRCODECHECKACTIVITY, 0, bundle);
//            JumpUtils.gotoNeedGesture(PureTextWebViewActivity.this, Constants.QRCODEACTIVITY, bundle);
            JumpUtils.jumptoNatvie(PureTextWebViewActivity.this, Constants.QRCODEACTIVITY ,1 ,bundle);

        }

        @JavascriptInterface
        public void goWriteCard(String data) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    //去写卡
                    backEvent();
                    CardInfo cardInfo = new Gson().fromJson(data, CardInfo.class);
                }
            });
        }

        //农行支付
        @JavascriptInterface
        public void ABCPay(String data) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    wxPayBean = new Gson().fromJson(data, WXPayBean.class);

                    /**
                     * 判断手机上是否具备调起农行掌银的条件
                     */
                    if (BankABCCaller.isBankABCAvaiable(PureTextWebViewActivity.this)) {

                        /**
                         * 调起农行掌银
                         */
                        BankABCCaller.startBankABC(PureTextWebViewActivity.this,
                                //Android为第三方apk的包名。
                                PureTextWebViewActivity.this.getPackageName(),
                                //CallbackID：支付完成后回调用的id ,Android 为第三方APP目标页面的activity。
                                PureTextWebViewActivity.this.getClass().getName(),
                                //业务类型。目前支持的取值仅为pay，
                                "pay",
                                //支付订单号。
                                wxPayBean.getToken());
                    } else {//客户手机未安装农行掌银APP的处理逻辑，由第三方APP自行实现
                        Toast.makeText(PureTextWebViewActivity.this,
                                "没安装农行掌银，或已安装农行掌银版本不支持",Toast.LENGTH_LONG).show();
                    }

                }
            });
        }

        //招行 付款
        @JavascriptInterface
        public void CMBPay(String data) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    wxPayBean = new Gson().fromJson(data, WXPayBean.class);

                }
            });
        }

    }


    /**
     * 身份证数据
     */
    byte[] imageBytesFront;
    byte[] imageBytesBack;
    private boolean isUseLocal = false;
    JSONObject jsonPicPath = new JSONObject();

    public void saveIdCardPic2Cache(String json) {
        String backPic = "", frontPic = "", name = "";
        try {
            if (isUseLocal)
                name = json;
            else
                name = JsonUtils.getString(json, "File_Nm", "");
            if (null != imageBytesFront) {
                imageBytesFront = FileUtils.compressBitmap(imageBytesFront, 200);
                frontPic = FileUtils.writeImage2Cache(PureTextWebViewActivity.this, imageBytesFront, name + "_ZM");
//                FileUtils.writeImage2Disk(mContext, imageBytesFront, name + "_ZM");
            }
            if (null != imageBytesBack) {
                imageBytesBack = FileUtils.compressBitmap(imageBytesBack, 200);
                backPic = FileUtils.writeImage2Cache(PureTextWebViewActivity.this, imageBytesBack, name + "_FM");
//                FileUtils.writeImage2Disk(mContext, imageBytesBack, name + "_FM");
            }
            jsonPicPath.put("FrontPicPath", frontPic);
            jsonPicPath.put("BackPicPath", backPic);
            initFileUpload(json);
            uploadFiles(REQUEST_CODE_IDCARD_SIDE_FRONT);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    CookieStore cookieStore = new BasicCookieStore();

    public void uploadFiles(final int type) {
        String filePath = "";
        try {
            if (type == REQUEST_CODE_IDCARD_SIDE_FRONT) {
                filePath = jsonPicPath.getString("FrontPicPath");
                fileUploadEntity.File_Nm = fileNm + "_ZM.jpg";
            } else if (type == REQUEST_CODE_IDCARD_SIDE_BACK) {
                filePath = jsonPicPath.getString("BackPicPath");
                fileUploadEntity.File_Nm = fileNm + "_FM.jpg";

            }

            if (TextUtils.isEmpty(jsonPicPath.getString("FrontPicPath")))
                return;
            File imageFile = new File(filePath);

            MainController.getInstance().uploadFiles(cookieStore, imageFile, fileUploadEntity, new RequestCallBack<String>() {
                @Override
                public void onSuccess(ResponseInfo responString) {
                    Log.i("Polling", "upload file success responString" + responString.result.toString());
                    LoadingDialogUtils.getInstance().dismissLoading();

                    boolean isSuccess = false;
                    if (null != responString.result) {
                        String result = responString.result.toString();
                        isSuccess = JsonUtils.getBoolean(result, "SUCCESS", false);
                    }

                    if (isSuccess && REQUEST_CODE_IDCARD_SIDE_FRONT == type) {
                        uploadFiles(REQUEST_CODE_IDCARD_SIDE_BACK);
                        try {
                            FileUtils.deleteFile(jsonPicPath.getString("FrontPicPath"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else if (isSuccess && REQUEST_CODE_IDCARD_SIDE_BACK == type) {
                        try {
                            FileUtils.deleteFile(jsonPicPath.getString("BackPicPath"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        new Runnable() {
                            @Override
                            public void run() {
                                //上传身份证结果
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        wv_content.loadUrl("javascript:createPictureResult()");
                                    }
                                });
                            }
                        }.run();
                    } else {
                        new Runnable() {
                            @Override
                            public void run() {
                                //上传身份证结果
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        wv_content.loadUrl("javascript:errorHandle(" + null + "," + "'上传图片失败，请稍后尝试。'" + ")");
                                    }
                                });
                            }
                        }.run();
                    }
                }

                @Override
                public void onFailure(HttpException arg0, String arg1) {
                    Log.i("Polling", "upload file failure responString" + arg0.toString() + arg1);
                    LoadingDialogUtils.getInstance().dismissLoading();
                    new Runnable() {
                        @Override
                        public void run() {
                            //上传身份证结果
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    wv_content.loadUrl("javascript:errorHandle(" + null + "," + "'网络异常，请稍后尝试。'" + ")");
                                }
                            });
                        }
                    }.run();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    String fileNm = "";
    /**
     * 文件上传参数
     */
    FileUploadEntity fileUploadEntity;

    private void initFileUpload(String json) {
        fileUploadEntity = new FileUploadEntity();
        fileUploadEntity.USERID = JsonUtils.getString(json, "USERID", "");
        fileUploadEntity.BRANCHID = JsonUtils.getString(json, "BRANCHID", "");
        fileUploadEntity.TXCODE = JsonUtils.getString(json, "TXCODE", "");
        fileUploadEntity.File_Date = JsonUtils.getString(json, "File_Date", "");
        fileUploadEntity.CCB_IBSVersion = JsonUtils.getString(json, "CCB_IBSVersion", "");
        fileUploadEntity.ACTION = JsonUtils.getString(json, "ACTION", "");
        fileNm = JsonUtils.getString(json, "File_Nm", "");
    }


    public void initESafe() {
    }

    public void initPermissiont(String permission, int requestCode) {
        int permissionCheck = ContextCompat.checkSelfPermission(this, permission);
        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
            if (null != permissionListener)
                permissionListener.onPermissionDeny(requestCode);
            ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode);
        } else {
            if (null != permissionListener)
                permissionListener.onPermissionGranted(requestCode);
        }
    }

    private void initSecurityReq(String json) {
        initSecurityReq(json, null);
    }

    /**
     * 身份证数据
     */
    private IDCardEntity idCardEntity;
    String cardFace = "";
    String photo = "";

    private void initSecurityReq(String json, String type) {
        initSecurityReqBody(json);
        if (null == securityReq)
            initESafe();
        securityReq.BRANCHID = JsonUtils.getString(json, "BRANCHID", "");
        int faceType = JsonUtils.getInt(json, "FaceType", 2);
        if (null != type) {
            securityReq.TXCODE = HostAddress.TXCODE_ZX02;
        } else {
            securityReq.TXCODE = HostAddress.TXCODE;
        }

        if (faceType == 1 && null != idCardEntity) {
            securityReqBody.base64_Ecrp_Txn_Inf = cardFace;
        } else {
            securityReqBody.base64_Ecrp_Txn_Inf = photo;
        }
    }

    private void initSecurityReqBody(String json) {
        securityReqBody = JsonUtils.jsonToBean(json, SecurityReqBody.class);
        securityReqBody.SYSTEM_TIME = DateUtils.getCurrentDate(DateUtils.dateFormatTimeStamp);
        securityReqBody.HARDWARESN = DeviceUtils.getDeviceId(PureTextWebViewActivity.this);
    }

    CheckPermissionListener permissionListener = new CheckPermissionListener() {
        @Override
        public void onPermissionGranted(int requestCode) {
            switch (requestCode) {
                case READ_PHONE_STATE_CODE:
                    break;
                case FACE_CAMERA_REQUEST_CODE:
                    startfaceScan();
                    break;
                case REQUEST_CODE_IDCARD_SIDE_FRONT:
                    scanIDCard(REQUEST_CODE_IDCARD_SIDE_FRONT);
                    break;
                case REQUEST_CODE_IDCARD_SIDE_BACK:
                    scanIDCard(REQUEST_CODE_IDCARD_SIDE_BACK);
                    break;
                case REQUEST_CODE_BANK_CARD:
                    scanBandCard();
                    break;
            }
        }

        @Override
        public void onPermissionDeny(int requestCode) {

        }

        @Override
        public void onPermissionRequestResult(int requestCode, String[] permissions, int[] grantResults) {

        }
    };

    private void scanBandCard() {
    }

    private void scanIDCard(int code) {

    }

    String result = "";


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {

        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {

                        Toast.makeText(PureTextWebViewActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        String orderId1 = getOrderId();
                        String tradeType1 = getTradeType();

                        if (tradeType1 != null) {
                            if (tradeType1.equals("3")) {
                                wv_content.reload();
                                wv_content.loadUrl(Constant.BASE_URL + "app-front-end/#/charge/paySucc" + "?tradeType=" + tradeType1 + "&orderId=" + orderId1);
                            }
                            if (tradeType1.equals("1") | tradeType1.equals("2") | tradeType1.equals("4")|tradeType1.equals("5")) {
                                String access_token = ACache.get(PureTextWebViewActivity.this).getAsString("access_token");
                                wv_content.reload();

                                String url1 = Constant.BASE_URL + "app-front-end/#/card/paySucc" + "?tradeType=" + tradeType1 + "&orderId=" + orderId1;
                                wv_content.loadUrl(Constant.BASE_URL + "app-front-end/#/card/paySucc" + "?tradeType=" + tradeType1 + "&orderId=" + orderId1);
                                L.e(Constant.TAG, "--------------------" + url1);
                            } else if(tradeType1.equals("51")){
                                wv_content.reload();
                                wv_content.loadUrl(Constant.BASE_URL + "app-front-end/#/mdlPages/payResult" + "?tradeType=" + tradeType1 + "&orderId=" + orderId1);
                            } else if(tradeType1.equals("ngFinance")){
                                wv_content.reload();
                                wv_content.loadUrl(Constant.BASE_URL + "app-front-end/#/shoppingMall/result" + "?tradeType=" + tradeType1 + "&orderId=" + orderId1);
                            } else{

                            }
                        }

                    } else {
                        String orderId = getOrderId();
                        String tradeType = getTradeType();
                        wv_content.reload();
                        String url = Constant.BASE_URL + "app-front-end/#/payFail" + "?tradeType=" + tradeType + "&orderId=" + orderId;
                        wv_content.loadUrl(Constant.BASE_URL + "app-front-end/#/payFail" + "?tradeType=" + tradeType + "&orderId=" + orderId);

                    }
                    break;
                }

                default:
                    break;
            }
        }
    };

    //这是另一个 支付接口  使用sdk支付   是NG金融的
    //阿里回调
    private Handler mHandlerAlipayBySDK = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                //阿里授权回调
                case SDK_PAY_FLAG:
                    PayJsonBean payJsonBean = (PayJsonBean) msg.getData().getSerializable("payJsonBean");
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    if (TextUtils.equals(payResult.getResultStatus(), "9000")) {
                        Toast.makeText(PureTextWebViewActivity.this, "支付成功", Toast.LENGTH_LONG).show();
                        if(!TextUtils.isEmpty(payJsonBean.getSucceedUrl())){
                            wv_content.loadUrl(payJsonBean.getSucceedUrl());
                        }
                    }else{
                        Toast.makeText(PureTextWebViewActivity.this, payResult.getMemo(), Toast.LENGTH_LONG).show();
                        if(!TextUtils.isEmpty(payJsonBean.getFailedUrl())){
                            wv_content.loadUrl(payJsonBean.getFailedUrl());
                        }
                    }
                    break;
            }
        }
    };

    public String getTradeType() {
        String[] orderInfoArr = orderInfo.split(",");
        String s = orderInfoArr[1];
        String[] trade = s.split(":");
        String s1 = trade[1];
        String mTradeType = s1.replace("\"", "");

        Log.d("zdh", "tradeType====" + mTradeType);
        return mTradeType;
    }

    public String getOrderId() {
        String[] orderInfoArr = orderInfo.split(",");
        String orderIds = orderInfoArr[2];
        String[] strings = orderIds.split(":");
        String string = strings[1];
        String s2 = string.replace("\"", "");
        String orderId = s2.replace("}", "");
        Log.d("zdh", "orderId==" + orderId);
        return orderId;
    }

    private void gotoActivity(String url) {
        Intent intent = new Intent(this, YouzanActivity.class);
        intent.putExtra(YouzanActivity.KEY_URL, url);
        startActivity(intent);
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void onClick(final View v) {
        int id = v.getId();
        if (id == R.id.back) {
            backEvent();
        } else if (id == R.id.share_iv) {
            umShare("景点交通伴手礼，环游全城一卡全包",
                    "苏州通·转转卡",
                    getIntent().getStringExtra("shareUrl"), R.mipmap.app_icon);
        }
    }


    @Override
    public void onBackPressed() {

        backEvent();
    }
    private void backEvent(){
        if(isad){
            if (wv_content.canGoBack()&&!webTitle.getText().toString().contains("我的钱包")) {
                wv_content.goBack();
            } else {
                JumpUtils.jump(this, "main", 0);
                finish();
            }
        }else{
            if ("桂花分".equals(webTitle.getText().toString()) || "市民信用".equals(webTitle.getText().toString())) {
                finish();

                wv_content.clearCache(true);

                wv_content.clearHistory();

                wv_content.destroy();

                wv_content=null;
            } else {
                if (wv_content.canGoBack()&&!webTitle.getText().toString().contains("我的钱包")) {
                    wv_content.goBack();
                } else {
                    finish();
                }
            }

//                finish();
        }
    }
    public void startfaceScan() {
    }



    /**
     * 银行卡数据
     */
    private BankEntity bankEntity;

    public void setStatusBar(String s){
        if("white".equals(s)){
            ImmersionBar.with(this)
                    .fitsSystemWindows(true)
                    .statusBarDarkFont(true, 0f)
                    .statusBarColor(R.color.white).init();
        }else if("blue".equals(s)){
            ImmersionBar.with(this)
                    .fitsSystemWindows(true)
                    .statusBarDarkFont(false, 0f)
                    .statusBarColor(R.color.color_2184FA).init();
        }

    }
    public void setTitleBar(String s){//web标题栏  白色与蓝色
        if("white".equals(s)){
//            toolbar
            back.setImageDrawable(PureTextWebViewActivity.this.getResources().getDrawable(R.drawable.icon_as_back));
            webTitle.setTextColor(PureTextWebViewActivity.this.getResources().getColor(R.color.black));
            toolBar.setBackgroundColor(getResources().getColor(R.color.white));
            v_statusBar.setBackgroundColor(ContextCompat.getColor(this,R.color.white));
        }else if("blue".equals(s)){
            back.setImageDrawable(PureTextWebViewActivity.this.getResources().getDrawable(R.drawable.icon_back_white));
            webTitle.setTextColor(PureTextWebViewActivity.this.getResources().getColor(R.color.white));
            toolBar.setBackgroundColor(getResources().getColor(R.color.color_2184FA));
            v_statusBar.setBackgroundColor(ContextCompat.getColor(this,R.color.color_2184FA));
        }

    }

    WXPayBean wxPayBean;

    //微信支付回调
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void get(String flag){
        int i = Integer.parseInt(flag);

        if(wxPayBean!=null){
            switch (i){
                case 0:
                    if(wxPayBean.getTradeType().equals("2")){
                        wv_content.loadUrl(Constant.BASE_URL + "app-front-end/#/card/paySucc" +
                                "?tradeType=" + wxPayBean.getTradeType() +
                                "&orderId=" + wxPayBean.getOrderId());
                    }else{
                        String newUrl = wxPayBean.getSucceedUrl();
                        if(wxPayBean.getSucceedUrl().indexOf("?")>-1){
                            newUrl +="&access_token=" +
                                    ACache.get(DaggerApplication.getIns()).getAsString("access_token");
                        }else{
                            newUrl +="?access_token=" +
                                    ACache.get(DaggerApplication.getIns()).getAsString("access_token");
                        }
                        wv_content.loadUrl(newUrl);
                    }
                    break;
                case -1:
                case -2:
                    if(wxPayBean.getTradeType().equals("2")){
                        wv_content.loadUrl(Constant.BASE_URL + "app-front-end/#/payFail" +
                                "?tradeType=" + wxPayBean.getTradeType() + "&orderId=" + wxPayBean.getOrderId());
                    }else{
                        String newUrl = wxPayBean.getFailedUrl();
                        if(wxPayBean.getFailedUrl().indexOf("?")>-1){
                            newUrl +="&access_token=" +
                                    ACache.get(DaggerApplication.getIns()).getAsString("access_token");
                        }else{
                            newUrl +="?access_token=" +
                                    ACache.get(DaggerApplication.getIns()).getAsString("access_token");
                        }
                        wv_content.loadUrl(newUrl);
                    }
                    break;
            }
        }
    }

    //农行 callback
    private void ABC_callBack(){
        String param = getIntent().getStringExtra("from_bankabc_param");
        if (!TextUtils.isEmpty(param)) {
            AbcPayResult abcPayResult = new AbcPayResult(param);
            if (abcPayResult.isSuccessful()) {
                // 支付成功
                get("0");
//                Toast.makeText(this, "支付成功", Toast.LENGTH_SHORT).show();
            } else if (!TextUtils.isEmpty(abcPayResult.getMsg())) {
                // 支付失败，提示原因
                get("-1");
//                Toast.makeText(this, abcPayResult.getMsg(), Toast.LENGTH_SHORT).show();
            } else {
                get("-1");
                Log.e("bank ABC", "支付失败 其他原因 "+abcPayResult.getMsg()+":"+abcPayResult.getSTT() );
            }
        }
    }

    //招行回调    招行在AndroidManifest 配置scheme  招行会给唯一的
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
    }

}

